#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tpf_meta.py 
@version:
@time: 2022/04/29 
"""
from TapClientCore.T05_TM_feature.v2.TMF06_meta_instances.tmf_meta_instances import TMFInstances


class TPFMeta(TMFInstances):

    # 通过table精确查询
    def search_table_spec(self, keyword):
        response = self._get_metadataInstances_search('table', keyword)
        for one in response:
            if one.get('table').get('original_name') == keyword:
                return one.get('id')

    # 通过table查询meta_id 匹配
    def search_table_only_by_meta_id(self, keyword, meta_id):
        response = self.get_metadataInstances_search_table(keyword)
        for one in response:
            if one.get('id') == meta_id:
                return one
        from TapUtil.logfunc.logger import logger
        logger.fatal('Not found')
        raise

        # 通过column查询meta_id 匹配

    def search_column_only_by_meta_id(self, keyword, meta_id):
        last_id = None
        while True:
            response = self.get_metadataInstances_search_column(keyword, last_id)
            print(response)
            if response:
                for one in response:
                    print(one)
                    if one.get('id') == meta_id:
                        return one
                last_id = response[-1].get('id')
            else:
                from TapUtil.logfunc.logger import logger
                logger.fatal('Not found')
                raise

    # 根据meta_id查询fields，pop id
    def get_meta_fields_by_id(self, meta_id):
        response = self.get_metadataInstances_find_table_by_id(meta_id)
        # 去除字段id
        fields = response.get('fields')
        for field in fields:
            field.pop('id')
        return fields

    # 根据meta_id查询fields，不pop id
    def get_meta_fields_not_pop_id_by_id(self, meta_id):
        response = self.get_metadataInstances_find_table_by_id(meta_id)
        # 去除字段id
        fields = response.get('fields')
        return fields

    # 通过meta获取所有的field_name
    def get_all_field_name_by_id(self, meta_id):
        """
        :param meta_id:
        :return:
        """
        response = self.get_meta_fields_by_id(meta_id)
        tmp = []
        for field in response:
            tmp.append(field.get('field_name'))
        return tmp

    # 通过meta id获取字段中的第一个字段名
    def get_field_name_by_id(self, meta_id):
        """
        :param meta_id:
        :return:
        """
        response = self.get_meta_fields_by_id(meta_id)
        return response[0].get('field_name')

    # 通过meta_id 修改 meta
    def patch_meta_fields_by_id(self, meta_id, payload):
        _payload = {'fields': [payload], 'relation': []}
        self.patch_metadataInstances_by_id(meta_id, _payload)
